package com.atguigu.tingshu.account.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: atguigu
 * @create: 2024-05-09 15:30
 */
@Slf4j
@Component
public class AccountReceiver {


    @Autowired
    private UserAccountService userAccountService;

    /**
     * 用户首次注册后监听初始化账户消息
     * 完成账户保存
     * 1.是否需要幂等性处理 2.是否需要事务管理
     * 监听到数据：“{"amount":100,"orderNo":"zs1788470360074436608","title":"新用户注册，赠送礼金","userId":16}”
     *
     * @param record
     */
    @KafkaListener(
            topics = KafkaConstant.QUEUE_USER_REGISTER
    )
    public void userRegiger(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            //将JSON数据转为Java Map对象
            Map map = JSON.parseObject(value, Map.class);
            userAccountService.saveUserAccount(map);
        }
    }


}
